//
//  HZApiManager.m
//  HZTC_YaDeArt
//
//  Created by MayerF on 17/3/28.
//  Copyright © 2017年 HZTC. All rights reserved.
//

#import "HZApiManager.h"
#import "HZApiTool.h"

@interface HZApiManager()
@property (nonatomic, strong)NSMutableDictionary *pTimerDict;
@end

@implementation HZApiManager

+ (instancetype)manager
{
    static HZApiManager *pManager = nil;
    @synchronized (self) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            pManager = [[HZApiManager alloc] init];
        });
    }
    
    return pManager;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        _Session = nil;
        _pTimerDict = [NSMutableDictionary dictionary];
    }
    return self;
}

+ (void)apiPostParams:(NSDictionary *)params
              success:(void (^)(id objc))success
              failure:(void (^)(NSError *error))failure
{
    [[HZApiManager manager] apiPostParams:params success:success failure:failure];
}

- (NSURLSessionDataTask *)apiPostParams:(NSDictionary *)params
                                success:(void (^)(id objc))success
                                failure:(void (^)(NSError *error))failure
{
    NSString *pFunction = nil;
    if ([params.allKeys containsObject:kAPIFuctionKey]) {
        pFunction = [params valueForKey:kAPIFuctionKey];
    }
    NSMutableDictionary *newParams = [params mutableCopy];
    if ([HZApiManager manager].Session) {
        [newParams setValue:[HZApiManager manager].Session forKey:@"sessionId"];
    }
    NSString *pUrl = [NSString stringWithFormat:@"%@%@",[HZUserManager getAPIHost],pFunction];
    NSURLSessionDataTask *task = [HZApiTool postJsonUrl:pUrl params:(NSDictionary *)newParams success:^(id x) {
        //针对接口文档定制
        ///////
        NSDictionary *dict = (NSDictionary *)x;
        if ([dict.allKeys containsObject:@"code"] &&
            [dict.allKeys containsObject:@"result"]) {
            
            NSString *pCode = [dict valueForKey:@"code"];
            id result = [dict valueForKey:@"result"];
            if ([pCode isEqualToString:@"0000"]) {
                [self p_saveSessionResult:result];
                if (success) {
                    if ([result isEqual:[NSNull null]]) {
                        success(nil);
                    }else {
                        success(result);
                    }
                }
            }else if([dict.allKeys containsObject:@"msg"]){
                
                [self p_clearSessionWithCode:pCode];
                NSString *pMsg = [dict valueForKey:@"msg"];
                NSError *pError = [NSError errorWithDomain:pMsg code:[pCode integerValue] userInfo:nil];
                if (failure) {
                    failure(pError);
                }
            }
        }else {
            if (success) {
                success(x);
            }
        }
        ///////
    } failure:^(NSError *error) {
        DLog(@"error==%@===%ld",error.domain,(long)error.code);
        error = [NSError errorWithDomain:@"网络错误" code:error.code userInfo:error.userInfo];
        if (error.code == -999) {
            DLog(@"请求取消");
        }else if (failure) {
            failure(error);
        }
    }];
    
    return task;
}

- (void)p_saveSessionResult:(id)result
{
    if ([result isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dict = (NSDictionary *)result;
        if ([dict.allKeys containsObject:@"session"]) {
            NSString *pSession = [dict valueForKey:@"session"];
            [HZApiManager manager].Session = pSession;
        }
    }
}

- (void)p_clearSessionWithCode:(NSString *)code
{
    if ([code isEqualToString:@"1006"]) {//session过期
        [HZApiManager manager].Session = nil;
        [HZUserManager manager].isLogined = NO;
    }
}

#pragma mark -
#pragma mark NSTimer
#define kAPI_Timer @"api_timer"
#define kAPI_Params @"api_params"
#define kAPI_Success @"api_success"
#define kAPI_Failure @"api_failure"
#define kAPI_UrlSession @"api_urlSession"
+ (void)timerRemoveAll
{
    NSArray *pKeys = [HZApiManager manager].pTimerDict.allKeys;
    for (NSString *key in pKeys) {
        NSDictionary *tempDict = [[HZApiManager manager].pTimerDict valueForKey:key];
        NSTimer *tempTimer = [tempDict valueForKey:kAPI_Timer];
        [tempTimer invalidate];
        tempTimer = nil;
        if ([tempDict.allKeys containsObject:kAPI_UrlSession]) {
            NSURLSessionDataTask *tempTask = [tempDict valueForKey:kAPI_UrlSession];
            [tempTask cancel];
        }
        [[HZApiManager manager].pTimerDict removeObjectForKey:key];
    }
}

+ (void)timerSuspend
{
    NSArray *pKeys = [HZApiManager manager].pTimerDict.allKeys;
    for (NSString *key in pKeys) {
        NSDictionary *tempDict = [[HZApiManager manager].pTimerDict valueForKey:key];
        NSTimer *tempTimer = [tempDict valueForKey:kAPI_Timer];
        [tempTimer setFireDate:[NSDate distantFuture]];
    }
}

+ (void)timerStart
{
    NSArray *pKeys = [HZApiManager manager].pTimerDict.allKeys;
    for (NSString *key in pKeys) {
        NSDictionary *tempDict = [[HZApiManager manager].pTimerDict valueForKey:key];
        NSTimer *tempTimer = [tempDict valueForKey:kAPI_Timer];
        [tempTimer setFireDate:[NSDate distantPast]];
    }
}

//定时请求
+ (void)timerPostParams:(NSDictionary *)params
                   time:(NSTimeInterval)time
               isRepeat:(BOOL)isRepeat
                success:(void (^)(id objc))success
                failure:(void (^)(NSError *error))failure
{
    //获取功能号，以功能号为key
    NSString *pFunction = nil;
    if ([params.allKeys containsObject:kAPIFuctionKey]) {
        pFunction = [params valueForKey:kAPIFuctionKey];
    }
    //清除同一功能号的定时器
    if ([[HZApiManager manager].pTimerDict.allKeys containsObject:pFunction]) {
        NSDictionary *tempDict = [[HZApiManager manager].pTimerDict valueForKey:pFunction];
        NSTimer *tempTimer = [tempDict valueForKey:kAPI_Timer];
        [tempTimer invalidate];
        tempTimer = nil;
        //取消同一功能号的urlsession
        if ([tempDict.allKeys containsObject:kAPI_UrlSession]) {
            NSURLSessionDataTask *tempTask = [tempDict valueForKey:kAPI_UrlSession];
            [tempTask cancel];
        }
        //移除之前的同一功能号
        [[HZApiManager manager].pTimerDict removeObjectForKey:pFunction];
    }
    
    NSTimer *pTimer = [NSTimer timerWithTimeInterval:time target:[HZApiManager manager] selector:@selector(timerAction:) userInfo:pFunction repeats:isRepeat];
    [[NSRunLoop mainRunLoop] addTimer:pTimer forMode:NSRunLoopCommonModes];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                 pTimer, kAPI_Timer,
                                 params, kAPI_Params,
                                 [success copy], kAPI_Success,
                                 [failure copy], kAPI_Failure, nil];
    [[HZApiManager manager].pTimerDict setValue:dict forKey:pFunction];
    
    [pTimer fire];
    
    DLog(@"key==%@",[HZApiManager manager].pTimerDict.allKeys);
}

- (void)timerAction:(NSTimer *)timer
{
    NSString *pFunction = timer.userInfo;
    NSMutableDictionary *tempDict = [[HZApiManager manager].pTimerDict valueForKey:pFunction];
    NSURLSessionDataTask *task = [self apiPostParams:[tempDict valueForKey:kAPI_Params] success:[tempDict valueForKey:kAPI_Success] failure:[tempDict valueForKey:kAPI_Failure]];
    //添加 sessiontask到字典中
    [tempDict setValue:task forKey:kAPI_UrlSession];
}


@end
